/**
 * 全局唯一axios实例
 */

import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElLoading } from 'element-plus'
import base from '@/utils/utils'

const BASE_URL = process.env.NODE_ENV === 'production' ? '' : ''

const instance = axios.create({
  baseURL: BASE_URL,
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
  timeout: 5 * 1000
})

let loading: any

// loading 参数类型
interface Options {
  target?: string | HTMLElement
  lock?: boolean
  text: string
  spinner?: string
  fullscreen: boolean
  background: string

}
// loading 参数
const options: Options = {
  text: '加载中...',
  fullscreen: true,
  background: 'rgba(0, 0, 0, .75)'
}

const beginLoading = () => {
  loading = ElLoading.service(options)
}
const endLoading = () => {
  loading.close()
}

instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    beginLoading()
    const token = base.getSessionStorage('token')
    config.headers.token = token
    return config
  },
  (error: any) => {
    endLoading()
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    endLoading()
    const res = response.data
    if (response.status === 200) {
      return res
    }
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

export default instance
